#include "levelstate.h"

LevelState::LevelState(GameEngine* engine) : GameState(engine)
{
	m_server = nullptr;
	m_client = nullptr;
	m_level = nullptr;

	m_shutdown_network_on_state_end = true;

	m_time_running = 0.0f;
	m_opened = false;
	m_release_started = false;
}

LevelState::~LevelState()
{
	if (m_is_server)
		ServerCleanup();
	else
		ClientCleanup();

	if (m_shutdown_network_on_state_end)
	{
		delete m_level;
	}
}

void LevelState::Init(bool is_server, RakNetServer* server, RakNetClient* client,
								ClientConnectionList client_list, Level* level)
{
	// Take the information from the previous state. Server and/or client might be nullpointers.
	m_is_server = is_server;
	m_server = server;
	m_client = client;
	m_client_list = client_list;

	m_level = level;

	if (m_is_server)
		ServerInit();
	else
		ClientInit();

	// Create the Lems of the level.
	for (int i = 0; i < m_level->player_number; i++)
	{
		m_lems.AddPlayer(m_level, i, m_level->player_info.at(i).number_of_lems);
	}
}

void LevelState::HandleInput(ALLEGRO_EVENT next_event)
{
}

void LevelState::Update(float timing_factor)
{
	if (m_is_server)
		ServerUpdate(timing_factor);
	if (m_client)
		ClientUpdate(timing_factor);

	m_time_running += timing_factor;

	// Update the level.
	m_level->Update(timing_factor);

	// Check if a new lem is spawned.
	for (std::vector<Entry*>::iterator it = m_level->entries.begin(); it != m_level->entries.end(); it++)
	{
		if ((*it)->new_lem())
		{
			// If so, spawn it at the right position.
			m_lems.lems.at((*it)->player_number() - 1).at((*it)->lems_spawned() - 1)
				->Spawn((*it)->spawn_position_x(), (*it)->spawn_position_y());

			// Don't spawn me again.
			(*it)->set_new_lem(false);
		}
	}

	m_lems.UpdateAll(timing_factor);
}

void LevelState::Draw()
{
	m_level->Draw();
	m_lems.DrawAll();
}